package cn.com.jit;

import java.util.*;
import java.util.regex.*;

public class SqlParser {

    /**
     * 解析SQL语句中的字段、聚合函数及约束条件。
     * 
     * @param sql SQL语句
     * @return 包含字段列表、聚合函数列表和约束条件的Map
     */
    public static Map<String, List<String>> parseSql(String sql) {
        Map<String, List<String>> result = new HashMap<>();
        result.put("fields", new ArrayList<>());
        result.put("aggregates", new ArrayList<>());
        result.put("conditions", new ArrayList<>());

        // 匹配SELECT子句中的字段和聚合函数
        Pattern selectPattern = Pattern.compile("SELECT\\s+((?:[^\\s(),]+\\(.*?\\)|[^\\s(),]+)(?:\\s*,\\s*(?:[^\\s(),]+\\(.*?\\)|[^\\s(),]+))*)", Pattern.CASE_INSENSITIVE);
        Matcher selectMatcher = selectPattern.matcher(sql);
        if (selectMatcher.find()) {
            String fieldsAndAggregates = selectMatcher.group(1);
            String[] items = fieldsAndAggregates.split("\\s*,\\s*");
            for (String item : items) {
                if (item.matches("[A-Z]+\\(.*?\\)")) {
                    result.get("aggregates").add(item.trim());
                } else {
                    result.get("fields").add(item.trim());
                }
            }
        }

        // 匹配WHERE子句中的条件
        Pattern wherePattern = Pattern.compile("WHERE\\s+(.+)", Pattern.CASE_INSENSITIVE);
        Matcher whereMatcher = wherePattern.matcher(sql);
        if (whereMatcher.find()) {
            String conditions = whereMatcher.group(1);
            String[] conditionArray = conditions.split("\\s+AND\\s+|\\s+OR\\s+");
            for (String condition : conditionArray) {
                result.get("conditions").add(condition.trim());
            }
        }

        return result;
    }

    public static void main(String[] args) {
        String sql = "SELECT name, MAX(age), MIN(salary) FROM users WHERE age > 20 AND gender = 'male'";
        Map<String, List<String>> parsedResult = parseSql(sql);
        
        System.out.println("Fields: " + parsedResult.get("fields"));
        System.out.println("Aggregates: " + parsedResult.get("aggregates"));
        System.out.println("Conditions: " + parsedResult.get("conditions"));
    }
}
